<template>
  <div>
    <div class="header">
      <h2>我的流程</h2>
      <el-button type="primary" @click="showCreateDialog">
        新建流程
      </el-button>
    </div>

    <el-table :data="workflows" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="type" label="类型" width="120" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            size="small"
            @click="viewWorkflow(scope.row.id)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="createDialogVisible"
      title="新建流程"
      width="500px"
    >
      <el-form :model="createForm" label-width="120px">
        <el-form-item label="创建方式">
          <el-radio-group v-model="createMethod">
            <el-radio label="template">使用模板</el-radio>
            <el-radio label="type">基础流程</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <template v-if="createMethod === 'template'">
          <el-form-item label="选择流程模板">
            <el-select v-model="createForm.template_id" placeholder="请选择流程模板">
              <el-option 
                v-for="template in templates" 
                :key="template.id" 
                :label="template.name" 
                :value="template.id"
                :disabled="template.status !== 'published'"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="表单数据" v-if="createForm.template_id">
            <el-input
              type="textarea"
              v-model="variablesJson"
              :rows="5"
              placeholder="请输入JSON格式的表单数据"
            ></el-input>
          </el-form-item>
        </template>
        
        <template v-else>
          <el-form-item label="流程类型">
            <el-select v-model="createForm.type" placeholder="请选择流程类型">
              <el-option label="请假申请" value="leave" />
              <el-option label="报销申请" value="expense" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createWorkflow">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const workflows = ref([])
const templates = ref([])
const createDialogVisible = ref(false)
const createMethod = ref('template')
const variablesJson = ref('{}')

const createForm = ref({
  type: '',
  template_id: null
})

const getStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'completed': 'success',
    'rejected': 'danger'
  }
  return types[status] || 'info'
}

const fetchWorkflows = async () => {
  try {
    const response = await axios.get('/workflow/instances')
    workflows.value = response.data
  } catch (error) {
    ElMessage.error('获取流程列表失败')
    console.error(error)
  }
}

const fetchTemplates = async () => {
  try {
    const response = await axios.get('/workflow/templates')
    templates.value = response.data
  } catch (error) {
    ElMessage.error('获取模板列表失败')
    console.error(error)
  }
}

const showCreateDialog = () => {
  createForm.value = {
    type: '',
    template_id: null
  }
  variablesJson.value = '{}'
  createMethod.value = 'template'
  createDialogVisible.value = true
}

const createWorkflow = async () => {
  try {
    let requestData = {}
    
    if (createMethod.value === 'template') {
      if (!createForm.value.template_id) {
        ElMessage.warning('请选择流程模板')
        return
      }
      
      requestData = {
        template_id: createForm.value.template_id
      }
      
      // 添加变量数据
      try {
        const variables = JSON.parse(variablesJson.value)
        requestData.variables = variables
      } catch (e) {
        ElMessage.error('表单数据JSON格式不正确')
        return
      }
    } else {
      if (!createForm.value.type) {
        ElMessage.warning('请选择流程类型')
        return
      }
      
      requestData = {
        type: createForm.value.type
      }
    }
    
    const response = await axios.post('/workflow/instances', requestData)
    ElMessage.success('流程创建成功')
    createDialogVisible.value = false
    fetchWorkflows()
    
    // 如果创建成功，跳转到流程详情页
    if (response.data && response.data.workflow_id) {
      router.push(`/workflow/${response.data.workflow_id}`)
    }
  } catch (error) {
    console.error('流程创建失败:', error)
    ElMessage.error('流程创建失败: ' + (error.response?.data?.message || error.message))
  }
}

const viewWorkflow = (id) => {
  router.push(`/workflow/${id}`)
}

onMounted(() => {
  fetchWorkflows()
  fetchTemplates()
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 